<template>
  <a-space direction="vertical" size="large">
    <a-card title="链接发布" :bordered="true" style="width: 100%">
      <a-input id="url_link" v-model:value="link" disabled>
        <template #prefix>
          <LinkOutlined />
        </template>
      </a-input>

      <div class="button_warpper">
        <a-button type="primary" @click="handleCopy">复制</a-button>

        <a-button type="primary" @click="handleOpen">打开</a-button>
      </div>
    </a-card>

    <a-card title="二维码发布" :bordered="true" style="width: 100%">
      <div id="qrcode" :ref="onQRCodeRef"></div>

      <div class="button_warpper">
        <a-button type="primary" @click="download">点击下载</a-button>
      </div>
    </a-card>
  </a-space>
</template>
<script lang="ts">
import { LinkOutlined } from '@ant-design/icons-vue';
import { defineComponent } from 'vue';
import QRCode from 'qrcodejs2-fixes';

export default defineComponent({
  components: { LinkOutlined },
  props: {
    link: { type: String, default: '' },
    name: { type: String, default: '' },
  },
  emits: ['handleOpen', 'handleCopy'],
  setup(props, { emit }) {
    const handleOpen = () => {
      emit('handleOpen');
    };

    const handleCopy = () => {
      emit('handleCopy');
    };

    const onQRCodeRef = (div: HTMLDivElement | null) => {
      if (!div) {
        return;
      }
      div.innerHTML = '';

      new QRCode(div, {
        text: props.link,
        width: 100,
        height: 100,
        typeNumber: 4,
        correctLevel: QRCode.CorrectLevel.L,
      });
    };

    const download = () => {
      const canvas = document
        .getElementById('qrcode')
        ?.getElementsByTagName('canvas')[0];

      const temp = document.createElement('a');
      if (!canvas) return;
      temp.href = canvas.toDataURL();
      temp.download = `${props.name}`;

      temp.click();
    };
    return { handleOpen, handleCopy, onQRCodeRef, download };
  },
});
</script>
<style lang="less" scoped>
.button_warpper {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px 0 0;
  button {
    margin-left: 24px;
  }
}
</style>
